<template>
  <div class="seckillall">
    <div class="head">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="账号" prop="userAcc">
          <el-input
            v-model="queryParams.userAcc"
            placeholder="请输入管理员账号"
            clearable
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="userName">
          <el-input
            v-model="queryParams.userName"
            placeholder="请输入管理员姓名"
            clearable
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="角色名称" prop="roleId">
                    <el-select v-model="queryParams.roleId" placeholder="请选择角色" filterable>
                        <el-option v-for="item in roleList" :label="item.roleName" :key="item.roleId"
                            :value="item.roleId"></el-option>
                    </el-select>
                </el-form-item>

        <el-form-item label="管理员状态" prop="userStatus">
          <el-select
            v-model="queryParams.userStatus"
            placeholder="请选择管理员状态"
            filterable
          >
            <el-option label="启用" value="0" ></el-option>
            <el-option label="禁用" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="default" @click="searchBtn()"
            >搜索</el-button
          >
          <el-button size="default" @click="resetBtn">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="middle">
        <div class="add" style="margin-left: 20px">
          <div class="button">
            <el-button type="primary" :icon="Plus" @click="handleAdd()" plain
              >新增</el-button
            >
          </div>
        </div>
        <div class="add">
          <div class="button">
            <el-button
              type="success"
              :icon="Edit"
              @click="handleEdit()"
              :disabled="single"
              plain
              >修改</el-button
            >
          </div>
        </div>
        <div class="add">
          <div class="button">
            <el-button
              type="danger"
              :icon="Delete"
              @click="handleDelete()"
              :disabled="multiple"
              plain
            >
              删除
            </el-button>
          </div>
        </div>
      </div>
      <div class="end">
        <el-table
          :data="tableData"
          row-key="userId"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" />
          <el-table-column label="序号" property="userId" width="70px">
            <!-- <template #default="scope">{{ scope.$index + 1 }}</template> -->
          </el-table-column>
          <el-table-column property="userAcc" label="管理员账号" width="120px"/>

          <el-table-column property="userName" label="管理员姓名" width="120px"/>
          <el-table-column property="userSex" label="性别" width="60px"/>

          <el-table-column property="userPhone" label="手机号" width="120px"/>
          <el-table-column property="userEmail" label="邮箱" width="180px"/>
          <el-table-column property="lastLoginTime" label="最后登录时间" :formatter="formatDate"/>
          <el-table-column property="createTime" label="创建时间" :formatter="formatDate"/>
          <el-table-column property="roles" label="角色" width="110px"/>
          <el-table-column label="状态" width="110px">
            <template #default="scope" >
              <template v-if="!isSuperAdmin(scope.row)">
              <el-button type="success" v-if="scope.row.userStatus == 0" plain 
               @click="handleStatus(scope.row)" >启用</el-button
              >
              <el-button type="warning" v-if="scope.row.userStatus == 1" plain @click="handleStatus(scope.row)" >禁用</el-button>
            </template>
             </template>
          </el-table-column>
          <el-table-column label="操作" width="110px">
            <template #default="scope">
              <el-button
                size="small"
                type="danger"
                @click="rePwd(scope.row)"
                v-if="!isSuperAdmin(scope.row)"
              >
                重置密码
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button size="small" @click="handleEdit(scope.row)" 
               v-if="!isSuperAdmin(scope.row)">
                修改
              </el-button>

              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row)"
                v-if="!isSuperAdmin(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-left: 600px">
          <div class="demo-pagination-block">
            <el-pagination
              v-model:current-page="queryParams.pageNum"
              v-model:page-size="queryParams.pageSize"
              :page-sizes="[5, 10, 20, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>

      <el-dialog v-model="dialogVisible" :modal="true" width="800px">
        <el-form :model="formData" :rules="rules" ref="categoryForm">
          <el-row>
            <el-col :span="16">
              <el-form-item label="姓名" label-width="120px" prop="userName">
                <el-input
                  v-model="formData.userName"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>

            <el-col :span="16">
              <el-form-item label="账号" label-width="120px" prop="userAcc">
                <el-input
                  v-model="formData.userAcc"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item label="性别" label-width="120px" prop="userSex">
                <el-select v-model="formData.userSex" filterable>
                  <el-option label="男" value="男"></el-option>
                  <el-option label="女" value="女"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="22">
              <el-form-item
                label="角色"
                label-width="120px"
              >
                <el-transfer v-model="value" :data="data" />
              </el-form-item>
            </el-col>
          </el-row>
                        <el-row>
            <el-col :span="16">
              <el-form-item label="手机号" label-width="120px" prop="userPhone">
                <el-input
                  v-model="formData.userPhone"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item label="邮箱" label-width="120px" prop="userEmail">
                <el-input
                  v-model="formData.userEmail"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item
                label="备注"
                label-width="120px"
                prop="userNote"
              >
                <el-input
                  v-model="formData.userNote"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleCanle">取消</el-button>
            <el-button type="primary" @click="handleConfirm"> 确认 </el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog v-model="deleteDialog" title="Tips" width="500">
        <span>确认要删除吗？</span>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="deleteDialog = false">取消</el-button>
            <el-button type="primary" @click="deleteConfirm"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog v-model="statusDialog" title="Tips" width="500">
        <span>确认要修改状态吗？</span>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="statusDialog = false">取消</el-button>
            <el-button type="primary" @click="StatusChange"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog v-model="rePwdDialog" title="Tips" width="500">
        <span>确认要重置密码吗?初始密码为:123456</span>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="rePwdDialog = false">取消</el-button>
            <el-button type="primary" @click="rePwd1"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup >

import { ref, onMounted, computed } from "vue";
import { Calendar, Search, Edit, Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs';
import {
  selectAllUser,
  selectAllRole,
  addUser,
  getUser,
  updateUser,
  updateUserPwd,
  deleteUser,
  updateUserStatus,
  getUserRole,
  addUserRole
} from "@/api/user";

//选择框
// const selectable = ref();
const categoryForm = ref(null);
const single = ref(true);
const multiple = ref(true);
const total = ref(10);
const dialogVisible = ref(false);
const data2 = ref({});//修改状态
const pwdData = ref({});//重置密码
const selected = ref("add");
//是否禁用表单
const disabled = ref(false);
const selectRow = ref([]);
const deleteDialog = ref(false);
const statusDialog = ref(false);
const rePwdDialog = ref(false);
const deleteRow = ref([]);
const roleList = ref([]);
const categoryList = ref([]);

/**
 * @typedef {{
 * roleId: number,  
 * roleName: string
 * }} RoleItem
 * /
 * @type {RoleItem[]} */

const data = ref(/* @type {RoleItem[]} */ ([])) // 用 JSDoc 类型断言
const value = ref(/* @type {number[]} */ ([]))



onMounted(async () => {
  await getRoleList();
//   await getAllCategory();
  await getUserList();
  await getAllRoles();

});

const addRoleList = ref({
  roleId: "",
  menuIds: String
});

const formatDate = (row, column, cellValue) => {
  return cellValue ? dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss') : '-';
};

const isSuperAdmin = (row) => {
  // 处理字符串格式角色（如："管理员,超级管理员"）
  if (typeof row.roles === 'string') {
    return row.roles.includes('超级管理员')
  }
  // 处理数组格式角色（如：["管理员", "超级管理员"]）
  return Array.isArray(row.roles) && row.roles.some(role => role === '超级管理员')
};

//查询参数
const queryParams = ref({

  userName: "",
  userAcc: "",
  roleName: "",
  userStatus: "",


  pageNum: 1,
  pageSize: 6,
    // roleId: "",
});
// 表单参数
var formData = ref({
  userId: "",
  userAcc: "",
  userName: "",
  userSex: "",
  userPwd: "",
  userPhone: "",
  userEmail: "",
  userNote: "",
  userStatus: "",
  createTime: "",
  lastLoginTime: "",
  roleId: "",
  roles: "",  
    roleName: "",
});


//表格参数
const tableData = ref([]);
//校验规则
const rules = {
  userName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  userAcc: [{ required: true, message: "请输入账号", trigger: "blur" }],
  userPwd: [
  { 
    required: true, 
    message: '请输入密码', 
    trigger: 'blur' 
  },
  { 
    min: 8, 
    message: '密码长度不能少于8位', 
    trigger: 'blur' 
  }
],
userPhone: [
    { 
      required: true, 
      message: '请输入手机号', 
      trigger: 'blur' 
    },
    { 
      pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, // 支持国际号码
      message: '请输入有效的手机号',
      trigger: 'blur' 
    }
  ],
userSex: [{ required: true, message: "请选择性别", trigger: "change" }],
  userEmail: [
    { 
      required: true, 
      message: '请输入邮箱', 
      trigger: 'blur' 
    },
    { 
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: '请输入有效的邮箱地址',
      trigger: 'blur' 
    }
  ]
};

// 修改
function handleEdit(row) {
  if (row == null) {
    row = selectRow.value[0];
  }
  disabled.value = true;
  selected.value = "edit";
  const data = {
    userId: row.userId,
  };
  getUser(data).then((res) => {
    formData.value = res.data.getUser[0];
  });
  getUserRole(data).then((res) => {
    let roles = res.data.getUserRole;
    const roleIds = roles.map(item => item.roleId);
    value.value = roleIds;
 
  dialogVisible.value = true;
  });
}
// 删除
function handleDelete(row) {
  if (row == null) {
    row = selectRow.value.map((item) => {
      return item.userId;
    });
  } else {
    row = [row.userId];
  }
  deleteRow.value = row;
  deleteDialog.value = true;
}
//删除确定(后端是修改状态)
function deleteConfirm() {
  deleteUser(deleteRow.value).then((res) => {
    if (res.code === 500) {
      ElMessage.error(res.message);
    } else {
      ElMessage.success("删除成功");
    }
    getUserList();
  });
  deleteDialog.value = false;
}

// 修改状态
function handleStatus(row) {
  let status1;
  if (row.userStatus == 1) {
    status1 = 0;  
  } else if (row.userStatus == 0) {
    status1 = 1;
  };
  const data = {
    userId: row.userId,
    userStatus: status1,
  };
  data2.value = data;
  statusDialog.value = true;
}
//确定修改状态
function StatusChange() {
  console.log(data2);
  updateUserStatus(data2.value).then((res) => {
    if (res.code === 500) {
      ElMessage.error(res.message);
    } else {
      ElMessage.success("修改成功");
    }
    getUserList();
  });
  statusDialog.value = false;
}
// 重置密码
function rePwd(row) { 
  const data = {
    userId: row.userId,
    userPwd: "123456",
  };
  pwdData.value = data;
  rePwdDialog.value = true;
}
//确定重置密码
function rePwd1() {
  updateUserPwd(pwdData.value).then((res) => {
    if (res.code === 500) {
      ElMessage.error(res.message);
    } else {
      ElMessage.success("修改成功");
    }
    getUserList();
  });
  rePwdDialog.value = false;
}

//新增
function handleAdd() {
  handleCanle(); 
  dialogVisible.value = true;
  selected.value = "add";
}
//每页条数变换
function handleSizeChange(val) {
  console.log("每页" + val + "条");
  queryParams.value.pageSize = val;
  queryParams.value.pageNum = 1;
  getUserList();
}
//每码变换
function handleCurrentChange(val) {
  console.log("第" + val + "页");
  queryParams.value.pageNum = val;
  getUserList();
}

//关闭dialog
function handleCanle() {
  dialogVisible.value = false;
  
  // 重置表单数据到初始状态
  formData.value = {
    userId: "",
    userAcc: "",
    userName: "",
    userSex: "",
    userPwd: "",
    userPhone: "",
    userEmail: "",
    userNote: "",
    userStatus: "",
    createTime: "",
    lastLoginTime: "",
    roleId: "",
    roles: "",
    roleName: "",
  };
  
  // 重置表单验证
  categoryForm.value?.resetFields();
  categoryForm.value?.clearValidate();
  
  // 清空角色选择
  value.value = [];
}

// 选中某一列
function handleSelectionChange(selected) {
  console.log(selected, selected.length);
  single.value = selected.length != 1;
  multiple.value = selected.length == 0;
  selectRow.value = selected;
}

function handleConfirm() {
  categoryForm.value.validate((valid) => {
    if (!valid) {
      ElMessage.warning("请填写完整");
      return;
    }
    if (selected.value === "add") {
      handleAddOperation();
    } else {
      handleUpdateOperation();
    }
  });
}
 function handleAddOperation() {
  const addData = {
          userId: formData.value.userId,
          roleIds: value.value,
          userAcc: formData.value.userAcc,
          userName: formData.value.userName,
          userSex: formData.value.userSex,
          userPhone: formData.value.userPhone,
          userEmail: formData.value.userEmail,
          userNote: formData.value.userNote,
        };
        
        addUser(addData).then((res) => {
          console.log(res);
          if (res.code === 500) {
            ElMessage.error(res.message);
          } else {
            ElMessage.success("新增成功");
          }
          getUserList();
          handleCanle();
        });
}

async function handleUpdateOperation() {
  try {
    const addData = {
      userId: formData.value.userId,
      roleIds: value.value
    };

    await Promise.all([
      addUserRole(addData),
      updateUser(formData.value)
    ]);

    ElMessage.success("更新成功");
    await getUserList();
    dialogVisible.value = false;
  } catch (error) {
    ElMessage.error(`更新失败: ${error.message}`);
  }
  handleCanle();
}



function searchBtn() {
  queryParams.value.pageNum = 1;
  getUserList();
}

function resetBtn() {
  queryParams.value = {
    roleName: "",
    userAcc: "",
    userName: "",
    pageNum: 1,
    userStatus: "",
    pageSize: queryParams.value.pageSize,
  };
  getUserList();
}


async function getUserList() {
  try {
    const res = await selectAllUser(queryParams.value);
    console.log(res.data.user.records,4324324);
    total.value = res.data.user.total;
    tableData.value = res.data.user.records;

  } catch (error) {
    console.log(error);
  }
}

async function getRoleList() {
  try {
    const res = await selectAllRole();
    roleList.value = res.data.roleList;
  } catch (e) {
    console.log(e);
  }
}

async function getAllRoles() {
  try {
    const res = await selectAllRole(data.value);
    data.value = res.data.roleList.map(item => ({
      key: item.roleId,
      label: item.roleName
    })).filter(item => item.label !== '超级管理员');;
  } catch (error) {
    console.error("获取菜单失败:", error);
  }
}

</script>

<style scoped>
.seckillall {
  height: 100%;
  width: calc(100% - 50px);
  /* background-color: pink; */
  float: left;
}

.head {
  margin-top: 20px;
  margin-left: 20px;
  width: calc(100% - 50px);
}

.middle {
  width: 100%;
  height: 8vh;
  /* background-color: antiquewhite; */
  margin-bottom: 20px;
}

.add {
  margin-top: 15px;
  margin-left: 45px;
  width: 5%;
  height: 50%;
  float: left;
}

.end {
  float: left;
  width: calc(100%);
}
</style>